<?php

namespace App\Http\Controllers\Contract;

use App\Helpers\ContractApiTrait;
use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Contract\CarContract;
use Modules\Car\Entities\CarOrder;
use Illuminate\Support\Facades\Http;

class CreateFlowsByTemplatesController extends Controller
{
    use ResponseData, ContractApiTrait;


    //
    public function createFlowsByTemplates(Request $request){
        if(empty($request->order_id)){
            return $this->failed('订单id不能为空');
        }
        $order=CarOrder::find($request->order_id);
        if(empty($order)){
            return $this->failed('订单id错误，订单不存在');
        }
        $data=$request->data;
        $data=is_array($data)?$data:json_decode($data,true);
        if (empty($data)){
            return $this->failed('业务数据不能为空');
        }
        // 只有合同过期后才能重复发起新合同（续租除外）
        $contentnums = CarContract::query()->where('order_id', $request->order_id)->where('flow_status','<>','DEADLINE')->count();
        if(!$request->filled('order_xz_id')&&$contentnums>0){
            return $this->failed('合同已经生成成功，请勿重复发起合同');
        }

        try {
//            $data['agent']=$this->getAgent();
            $requestData=$this->getRequestData('CreateFlowsByTemplates',$data);
            $response=Http::post($this->getQizongApiUrl(),$requestData);
            $resData=$response->json();
            if(isset($resData['code']) && $resData['code']==0){
                $this->createContractLog($order,$resData,$request->order_xz_id);
                return $this->success(['flow_id'=>$resData['data']['flowIds'][0]]);
            }
            $this->createContractErrorLog('发起合同失败',$resData,$request);
            return $this->failed($resData['msg']);
        }catch (\Exception $e){
            $error='file: '.$e->getFile().' line: '.$e->getLine().' msg: '.$e->getMessage();
            $this->createContractErrorLog('发起合同异常',['msg'=>$error],$request);
            return $this->failed($error);
        }

    }
    //
    public function createContractLog($order,$resData,$xzid)
    {
        CarContract::create([
            'order_id'=>$order->id,
            'order_xz_id'=>$xzid??null,
            'flow_id'=>$resData['data']['flowIds'][0],
            'flow_status'=>'INIT',
            'request_id'=>$resData['data']['requestId'],
            'preview_url'=>$resData['data']['previewUrls'][0],
        ]);
    }



}
